package com.yd.controller.sys;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;

import javax.imageio.ImageIO;

import net.coobird.thumbnailator.Thumbnails;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.yd.tool.UtsUuid;

/***
 * 图片上传，返回图片名称，每个页面的图片都调用此方法
 * @author shangruihua
 *
 */
@Controller
public class UpFileController {

	@RequestMapping("/sys/upfile")
	@ResponseBody
	public String sys_upfile(@RequestParam("file") MultipartFile file)
			throws IOException {
		JSONObject jsonObject = new JSONObject();
		// web项目跟目录//有spring才能用
		String wepath = System.getProperty("address.webapp");
		// 图片文件夹
		String imgwk = "ivwzs";
		String wjm = file.getOriginalFilename().substring(
				file.getOriginalFilename().lastIndexOf(".") + 1,
				file.getOriginalFilename().length());

		String uuid = UtsUuid.getUuid();

		// 拼接后台文件
		String pathName = wepath + imgwk + File.separator + uuid + "." + wjm;
		// 保存文件
		file.transferTo(new File(pathName));

		// 获取一个图片路径
		File srcFile = new File(pathName);
		// 获取图片大小
		long srcFileSize = srcFile.length();
		if (srcFileSize > 614400) {
			commpressPicCycle(pathName, 500, 0.8);
		}

		jsonObject.put("error", "0");
		jsonObject.put("filename", uuid + "." + wjm);
		return jsonObject.toString();
	}

	/**
	 * 
	 * @param desPath
	 *            目标图片地址
	 * @param desFileSize
	 *            指定图片大小，单位kb
	 * @param accuracy
	 *            精度，递归压缩的比率，建议小于0.9
	 * @throws IOException
	 */
	private static void commpressPicCycle(String desPath, long desFileSize,
			double accuracy) throws IOException {
		File srcFileJPG = new File(desPath);
		long srcFileSizeJPG = srcFileJPG.length();
		// 2、判断大小，如果小于500kb，不压缩；如果大于等于500kb，压缩
		if (srcFileSizeJPG <= desFileSize * 1024) {
			return;
		}
		// 计算宽高
		BufferedImage bim = ImageIO.read(srcFileJPG);
		int srcWdith = bim.getWidth();
		int srcHeigth = bim.getHeight();
		int desWidth = new BigDecimal(srcWdith).multiply(
				new BigDecimal(accuracy)).intValue();
		int desHeight = new BigDecimal(srcHeigth).multiply(
				new BigDecimal(accuracy)).intValue();

		Thumbnails.of(desPath).size(desWidth, desHeight)
				.outputQuality(accuracy).toFile(desPath);
		commpressPicCycle(desPath, desFileSize, accuracy);
	}

}